#!/usr/bin/env python

import sys
from wedewoba.app import BrowserApp

try:
    selector=None
    if len(sys.argv) == 1:
        sys.exit(0)
    if len(sys.argv) == 3:
        selector = sys.argv[2]
    url = sys.argv[1]


    app = BrowserApp()
    browser = app.browser

    # define waht should be done whenn loading finishes
    def getData(result):
        if result:
            if selector:
                el = browser.findFirstElement(selector)
            else:
                el = browser.page.mainFrame().documentElement()
            
            # get position and size
            g = browser.getAbsoluteElementGeometry(el)
            with open("test.geometry", "w+") as f: 
                f.write(str(g.x())+"\n"+str(g.y())+"\n")
                f.write(str(g.width())+"\n"+str(g.height())+"\n")

            #makebrowser screenshot
            browser.getElementImage(el).save("test.png")

            # get HTML
            with open("test.html", "w+") as f: 
                f.write(el.toOuterXml())

            #get plaintext
            with open("test.txt", "w+") as f: 
                f.write(el.toPlainText())
            
            app.quit()
        else:
            raise RuntimeError("Could not load page")
            app.exit(1)

    # to run the 'getData' function
    # you can use either the 'loadFinished' signal
    browser.loadFinished.connect(getData)
    # or the 'onloadFinished' method
    #browser.onloadFinished = getData

    app.run(url)

except Exception as e:
    print e
